package com.changgou.order.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/worder")
public class OrderController {

    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private OrderFeign orderFeign;

    @RequestMapping("/ready/order")
    public String ReadyOrder(Model model) {
        //将登录人的住址信息获取并返回到前端页面
        List<Address> addressList = addressFeign.list().getData();
        model.addAttribute("addressList", addressList);
        for (Address address : addressList) {
            if ("1".equals(address.getIsDefault())) {
                model.addAttribute("deAddr", address);
                break;
            }
        }

        //获取登录人购物车的信息,购物车一共有三个信息,订单项,总数量和总金额
        Map map = cartFeign.list();
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");
        Integer totalNum = (Integer) map.get("totalNum");
        Integer totalPrice = (Integer) map.get("totalPrice");
        model.addAttribute("carts", orderItemList);
        model.addAttribute("totalNum", totalNum);
        model.addAttribute("totalPrice", totalPrice);

        //返回前端页面
        return "order";
    }
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Order order) {
        return orderFeign.add(order);
    }
}
